﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;

namespace IDEAMS.common.converter
{
    public class DoubleToStrConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {

            double val = (double)value;


            string[] paramList = ((string)parameter).Split(',');
            if (paramList.Count() < 1 || paramList.Count() > 2)
            {
                throw new ArgumentException("parameter counts doesn't match");
            }

            string fmt = string.Format("{{{0}}}", paramList[0]);

            string nullIndicator = "-"; //默认值
            if (paramList.Count() == 2)
            {
                nullIndicator = paramList[1];
            }

            if (val.Equals(double.NaN)) return nullIndicator;

            string rn = string.Format(fmt, val);
            return rn;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string str = (string)value;
            double dVal = double.NaN;
            string nullIndicator = "-";

            try
            {

                string[] paramList = ((string)parameter).Split(',');
                if (paramList.Count() < 1 || paramList.Count() > 2)
                {
                    throw new ArgumentException("parameter counts doesn't match");
                }

                string fmt = string.Format("{{{0}}}", paramList[0]);

                if (paramList.Count() == 2)
                {
                    nullIndicator = paramList[1];
                }

                if (!string.IsNullOrEmpty(str) && !str.Equals(nullIndicator))
                {
                    dVal = double.Parse(str);
                }
                else
                {
                    dVal = double.NaN;
                }
            }
            catch (Exception)
            {
                dVal = double.NaN;
            }

            return dVal;
        }
    }
}
